<!-- 使用方法:

  showArea() {
        const defaultAreas = [
          { geoName: this.aftersaleInfo.stateProvinceGeoName, geoId: this.aftersaleInfo.stateProvinceGeoId },
          { geoName: this.aftersaleInfo.cityGeoName, geoId: this.aftersaleInfo.cityId },
          { geoName: this.aftersaleInfo.countyGeoName, geoId: this.aftersaleInfo.countyGeoId }
        ];
        ksAreaSelector.show(defaultAreas.filter(geo => geo.geoId))
          .then((selectedAreas) => {
            const returnApplications = Object.assign(this.aftersaleInfo,
              {
                stateProvinceGeoId: selectedAreas[0].geoId,
                stateProvinceGeoName: selectedAreas[0].geoName,
                cityId: selectedAreas[1].geoId,
                cityGeoName: selectedAreas[1].geoName,
                countyGeoId: selectedAreas[2].geoId || '',
                countyGeoName: selectedAreas[2].geoName
              });
            this.updateReturnApplications(returnApplications);
          })
          .catch((err) => {
            logger.error('选择地址失败', err);
          });
      }
-->
<template>
  <div>
    <!-- 遮罩 -->
    <div :class="[ isShow ? 'maskFadein' : 'initMask', 'mask' ]"
         @click="hide"></div>

    <div :class="[ 'areaselector' , isShow ? 'areaselector_toggle' : 'areaselector_init' ]">

      <!-- 标题栏 -->
      <div class="areaselector_header">
        <div class="areaselector_header_left" @click="hide">取消</div>
        <div class="areaselector_header_center">{{title}}</div>
        <div class="areaselector_header_right"
             @click="designate"
             :class="[ canSure ? '' : 'cant' ]">确定</div>
      </div>

      <div class="areaselector_body">
        <!-- 已选择地区 -->
        <div
          v-for="(geo, index) in selectedGeoList"
          :class="['selected-box', { current: currentTab === index }]"
          :key="index"
          @click="activeTab(index)"
        >
          {{geo.geoName}}
        </div>

        <!-- 请选择标签 -->
        <div
          v-if="selectedGeoList.length < maxDepth"
          :class="['selected-box', { current: currentTab === selectedGeoList.length }]"
          @click="activeTab(selectedGeoList.length)"
        >
          请选择
        </div>
      </div>

      <!-- 加载中... -->
      <div v-if="isLoading" class="areaselector__menu loading" >
        <div class="loading-box"></div>
      </div>

      <!-- 区域列表 -->
      <div v-else class="areaselector__menu" ref="menu">
        <div
          v-for="(geo, index) in currentGeoList"
          :class="['menu-item', { selected: isGeoItemSelected(index) }]"
          :key="index"
          @click="clickGeoItem(index)"
        >
          <span>{{geo.geoName}}</span>
          <i class="icon iconfont icon-area-check" v-if="isGeoItemSelected(index)"></i>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import { rem2px } from '../../utils/utility';
  import { getAreaByGeoId } from '../../api/user';

  export default {
    props: {
      title: {
        type: String,
        default: '所在地区'
      },
      maxDepth: {
        type: Number,
        default: 3
      }
    },

    data() {
      return {
        selectedGeoList: [],
        currentTab: 0,
        geoData: {},
        isLoading: false,
        isShow: false,
        canSure: false
      };
    },

    computed: {
      currentGeoList() {
        // 前一个页签的子列表
        const currentGeo = this.selectedGeoList[this.currentTab - 1];
        const parentGeoId = currentGeo ? currentGeo.geoId : 'CHN';
        return this.geoData[parentGeoId] || [];
      }
    },
    methods: {
      show(defaultGeoList) {
        this.selectedGeoList = [];
        if (defaultGeoList) {
          this.selectedGeoList = defaultGeoList;
        }

        const selectedLen = this.selectedGeoList.length;
        const activatedTabIndex = selectedLen < this.maxDepth ? selectedLen : selectedLen - 1;
//        this.$emit('shown');
        this.isShow = true;
        this.activeTab(activatedTabIndex);
      },
      hide() {
        this.isShow = false;
        const areaSelector = document.querySelector('.areaselector');
        const destroy = () => this.$destroy();
        if (areaSelector) {
          areaSelector.addEventListener('webkitTransitionEnd', destroy, false);
        }
      },

      // 滚动到已选地区
      scrollMenu() {
        if (!this.isLoading) {
          const parentGeoId = this.getParentGeoId(this.currentTab);
          const geoList = this.geoData[parentGeoId];
          const selectedGeo = this.selectedGeoList[this.currentTab];
          const defaultIndex = geoList.findIndex(geo => selectedGeo && selectedGeo.geoId === geo.geoId);
          this.$refs.menu.scrollTop = defaultIndex > -1 ? rem2px(0.95 * defaultIndex) : 0;
        }
      },

      // 判断标签是否激活
      isCurrentGeoTabActive(geoId) {
        const currentGeo = this.selectedGeoList[this.currentTab - 1] || { geoId: 'CHN' };
        return currentGeo.geoId === geoId;
      },

      // 拉取地区列表
      fetchGeoList(parentGeoId) {
        this.isLoading = true;
        getAreaByGeoId(parentGeoId)
          .then((res) => {
            if (this.currentTab === this.maxDepth - 1) {
                // 再最后一项增加'其它'选项 geoId为'ksqt'
//              res.data.unshift({
//                'geoId': 'ksqt',
//                'geoName': '其它',
//                'geoCode': '',
//                'parentGeoId': '',
//                'geoTypeName': 'County-Area'
//              });
              this.geoData = { ...this.geoData, [parentGeoId]: res.data };
            } else {
              this.geoData = { ...this.geoData, [parentGeoId]: res.data };
            }
            // 特殊地址
//            if (res.data.length < 1) {
//              this.canSure = true;
//            }
          })
//          .catch(e => $toast.show('地区数据获取失败, 请重试', 3000))
          .then(() => {
            // 只有停留在当前tab才隐藏加载中...
            if (this.isCurrentGeoTabActive(parentGeoId)) {
              this.isLoading = false;
            }
          });
      },

      // 选择省市区列表头
      activeTab(index) {
        this.isLoading = false;
        this.currentTab = index;
        this.canSure = false;

        const parentGeoId = this.getParentGeoId(index);
        // 如果该区域没有子项，拉取...
        if (!this.geoData[parentGeoId]) {
          this.fetchGeoList(parentGeoId);
        }
      },

      getParentGeoId(tabIndex) {
        const parentGeo = this.selectedGeoList[tabIndex - 1];
        return parentGeo ? parentGeo.geoId : 'CHN';
      },

      // 选择省、市或区列表的某一项
      clickGeoItem(index) {
        const parentGeoId = this.getParentGeoId(this.currentTab);
        this.selectedGeoList[this.currentTab] = this.geoData[parentGeoId][index];
        this.selectedGeoList = this.selectedGeoList.slice(0, this.currentTab + 1);
        if (this.currentTab === this.maxDepth - 1) {
          this.canSure = true;
          return;
        }
        this.activeTab(this.currentTab + 1);
      },
      designate() {
        if (!this.canSure) {
          return;
        }
        this.$emit('submit', this.selectedGeoList);
        this.hide();
      },

      isGeoItemSelected(index) {
        const currentGeo = this.currentGeoList[index];
        const selectedGeo = this.selectedGeoList[this.currentTab];
        const lastGeo = this.selectedGeoList[2] || '';
        if (lastGeo && lastGeo.geoId) {
          this.canSure = true;
        }
        return selectedGeo && selectedGeo.geoId === currentGeo.geoId;
      }
    },
    mounted() {
      this.$el.setAttribute('ks-area-selector', '');
    },
    destroyed() {
      document.body.removeChild(this.$el);
    },
    watch: {
      currentGeoList() {
        setTimeout(() => this.scrollMenu(), 0);
      }
    }
  };
</script>

<style lang="scss" scoped>
  .initMask {
    opacity: 1;
    display: none;
  }
  .maskFadein {
    opacity: 100;
    filter: alpha(opacity=100);
  }
  .mask {
    position: fixed;
    z-index: 1000;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.6);
  }
  .areaselector_toggle {
    -webkit-transform: translate(0, 0);
    transform: translate(0, 0);
  }
  .areaselector_init {
    -webkit-transform: translate(0, 100%);
    transform: translate(0, 100%);
  }
  .areaselector {
    position: fixed;
    left: 0;
    bottom: 0;
    -webkit-backface-visibility: hidden;
    backface-visibility: hidden;
    z-index: 5000;
    width: 100%;
    background-color: #fff;
    font-size: .26rem;
    -webkit-transition: -webkit-transform .3s;
    transition: -webkit-transform .3s;
    transition: transform .3s;
    transition: transform .3s, -webkit-transform .3s;
  }
  .areaselector_header {
    display: flex;
    padding: 0 0.26rem;
    justify-content: center;
    align-items: center;
    height: 0.9rem;
    .areaselector_header_center {
      flex: 1;
      text-align: center;
      font-size: .32rem;
      color: #282828;
    }
    .areaselector_header_right,
    .areaselector_header_left {
      width: 1rem;
      height: 100%;
      line-height: 0.9rem;
    }
    .areaselector_header_left {
      text-align: left;
      color: #888888;
    }
    .areaselector_header_right {
      text-align: right;
      color: #e43439;
    }
    .areaselector_header_right.cant {
      color: #282828;
    }
  }

  .areaselector_body {
    height: calc(.48rem + 2px);
    border-bottom: 1px solid #e6e6e6;
    .selected-box {
      display: inline-block;
      padding: 0 .06rem;
      margin-left: .48rem;
      line-height: .48rem;
      border-bottom-width: 2px;
      border-bottom-style: solid;
      border-bottom-color: transparent;
    }
    .selected-box.current {
      border-bottom-color: #e43439;
      color: #e43439;
    }
    .selected-box.hide {
      display: none;
    }
    .selected-box:first-child {
      margin-left: .2rem;
    }
  }
  .areaselector__menu {
    overflow-y: scroll;
    height: 4.65rem; /* 0.95*5 */
    &.loading {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .loading-box {
      width: 16px;
      height: 16px;
      /*background: url(../../assets/loading.gif) no-repeat 0 0;*/
      opacity: 0.64;
    }
    .menu-item {
      padding-left: .26rem;
      height: .95rem;
      line-height: .95rem;
    }
    .menu-item.selected {
      color: #e43439;
    }
  }
</style>
